#!/usr/bin/python3

import RPi.GPIO as GPIO
import lcd1602ForI2C as Lcd
import time

TRIG = 22
ECHO = 27


def setup():
    Lcd.init()
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(TRIG, GPIO.OUT)
    GPIO.setup(ECHO, GPIO.IN)


def distance():
    GPIO.output(TRIG, 0)
    time.sleep(0.000002)
    GPIO.output(TRIG, 1)
    time.sleep(0.00001)
    GPIO.output(TRIG, 0)
    while GPIO.input(ECHO) == 0:
        pass
    time1 = time.time()
    while GPIO.input(ECHO) == 1:
        pass
    time2 = time.time()
    during = time2 - time1
    return during * 340 / 2 * 100


def loop():
    while True:
        Lcd.write(0, 0, "Distance : " + str(int(distance())) + 'cm')
        time.sleep(1)


def destroy():
    GPIO.cleanup()
    Lcd.clear()


if __name__ == "__main__":
    setup()
    try:
        loop()
    except KeyboardInterrupt:
        destroy()
